﻿using System;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace HDTuyenChon.BL
{
	public class ImageUpload
	{
		string fileName;
		public ImageUpload()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		//This function is called from aspnet page, it takes directory name as parameter
		public string HandleUploadedFile(string directory)
		{
			// To get the root of the web site
			string root = HttpContext.Current.Server.MapPath("~/");
			// clean up the path
			if (!root.EndsWith(@"\"))
				root += @"\";
			// make a folder to store the images in
			string fileDirectory = root + @"\" + directory + "\\";
			// create the folder if it does not exist
			// make a link to the new file

			// loop through the file in the request
			for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
			{
				// get the file instance
				HttpPostedFile fi = HttpContext.Current.Request.Files.Get(i);
				
				// create a byte array to store the file bytes
				byte[] fileBytes = new byte[fi.ContentLength];
				
				// fill the byte array
				using (System.IO.Stream stream = fi.InputStream)
				{
					stream.Read(fileBytes, 0, fi.ContentLength);
				}
				// create a random file name
				fileName = Guid.NewGuid().ToString();

				// write the resized file to the file system
				File.WriteAllBytes(fileDirectory + fileName + "_thumb.jpg", ResizeImageFile(fileBytes, 75));
				fileBytes = null;				
			}
			return (fileName + "_thumb.jpg");
		}
		
		public void HandleUploadedFileUseExistingName(string directory, string fname)
		{
			// get the root of the web site
			string root = HttpContext.Current.Server.MapPath("~/");
			// clean up the path
			if (!root.EndsWith(@"\"))
				root += @"\";
			// make a folder to store the images in
			string fileDirectory = root + @"\" + directory + "\\";
			// loop through the file in the request
			for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
			{
				// get the file instance
				HttpPostedFile fi = HttpContext.Current.Request.Files.Get(i);
				// create a byte array to store the file bytes
				byte[] fileBytes = new byte[fi.ContentLength];				

				// fill the byte array
				using (System.IO.Stream stream = fi.InputStream)
				{
					stream.Read(fileBytes, 0, fi.ContentLength);
				}
				// create a random file name
				fileName = fname;
				// write the resized file to the file system
				File.WriteAllBytes(fileDirectory + fileName, ResizeImageFile(fileBytes, 75));
				fileBytes = null;
			}
		}

		/// This fuction returns a Byte array containing the resized file
		private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
		{
			using (System.Drawing.Image oldImage =
			System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
			{
				//If you want to maintain the propotion use following code
				//Size newSize = CalculateDimensions(oldImage.Size, targetSize);
				//If you want to use a fixed size use following one
				Size currentSize = new Size(oldImage.Width, oldImage.Height);
				Size newSize = GetDimension(currentSize);
				using (Bitmap newImage =
				new Bitmap(newSize.Width,
				newSize.Height, PixelFormat.Format24bppRgb))
				{
					using (Graphics canvas = Graphics.FromImage(newImage))
					{
						canvas.SmoothingMode = SmoothingMode.AntiAlias;
						canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
						canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
						canvas.DrawImage(oldImage,
						new Rectangle(new Point(0, 0), newSize));
						MemoryStream m = new MemoryStream();
						
						newImage.Save(m, ImageFormat.Jpeg);
						
						return m.GetBuffer();
					}
				}
			}
		}

		/// This function Calculates the new size of the image based on the target size
		private static Size CalculateDimensions(Size oldSize, int targetSize)
		{
			Size newSize = new Size();
			if (oldSize.Height > oldSize.Width)
			{
				newSize.Width =
				(int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
				newSize.Height = targetSize;
			}
			else
			{
				newSize.Width = targetSize;
				newSize.Height =
				(int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
			}
			return newSize;
		}

		//Dimension of the images can be set here
		private static Size GetDimension(Size imgSize)
		{
			Size newSize = new Size();			
			//Renew image width
			if (imgSize.Width < 300)
			{
				newSize.Width = imgSize.Width;
			}
			else
			{
				newSize.Width = 300;
			}
			//Renew image height
			if (imgSize.Height < 424)
			{
				newSize.Height = imgSize.Height;
			}
			else
			{
				newSize.Height = 424;
			}
			
			return newSize;
		}

	}
}



